package com.gitee.magic.framework.head.converter;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.converter.DocDescription;
import com.gitee.magic.framework.head.utils.TimeUtils;

/**
 * @author start
 */
@DocDescription(TimeUtils.YYYYMMDDHHMMSS)
public class LocalDateTimeConverterEditor extends AbstractConverterEditor<String> {

	public LocalDateTimeConverterEditor(Class<?> prototype) {
		super(prototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			Class<?> type=value.getClass();
			if(type.equals(String.class)) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern(TimeUtils.YYYYMMDDHHMMSS);
				setValue(LocalDateTime.parse(String.valueOf(value),df));
			}else {
				Date date = ((Date)value);
		        Instant instant = date.toInstant();
		        ZoneId zoneId = ZoneId.systemDefault();
				setValue(instant.atZone(zoneId).toLocalDateTime());
			}
		}
	}

	@Override
	public String converter() {
		if (getValue() == null) {
			return null;
		}
		return DateTimeFormatter.ofPattern(TimeUtils.YYYYMMDDHHMMSS).format((LocalDateTime)getValue());
	}
	
	@Override
	public Object getSource() {
		return converter();
	}
	
}
